package com.five.author.service.Impl;

import com.five.Page.Page;
import com.five.Page.PageList;
import com.five.author.mapper.AuthorMapper;
import com.five.author.mapper.NovelMapper;
import com.five.author.service.NovelService;
import com.five.exception.BusinessException;
import com.five.pojo.Author;
import com.five.pojo.Novel;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service("userNovelServiceImpl")
public class NovelServiceImpl implements NovelService {

    @Autowired
    private NovelMapper novelMapper;
    @Autowired
    private AuthorMapper authorMapper;


    @GlobalTransactional
    @Override
    public void insert(Novel novel) {
        if (novel.getTitle() == null){
            throw new BusinessException("标题不能为空");
        }
        novel.setCreateTime(LocalDateTime.now());
        novelMapper.insert(novel);
    }
    @GlobalTransactional
    @Override
    public void deleteById(Long id) {
        if (id == null){
            throw new BusinessException("id不能为空");
        }
        novelMapper.deleteById(id);
    }
    @GlobalTransactional
    @Override
    public void updateById(Novel novel) {
        if (novel.getId() == null){
            throw new BusinessException("id不能为空");
        }
        novel.setUpdateTime(LocalDateTime.now());
        novelMapper.updateById(novel);
    }

    @Override
    public Novel selectById(Long id) {
        Novel novel = novelMapper.selectById(id);
        return novel;
    }

    @Override
    public PageList<Novel> selectByPage(Page<Novel> page) {
        Integer totals = novelMapper.selectTotals();
        if (totals == null){
            return new PageList<>();
        }
        List<Novel> novels = novelMapper.selectByPage(page);
        return new PageList<>(totals,novels);
    }

    @Override
    public List<Novel> selectAll() {
        return novelMapper.selectAll();
    }

    @Override
    public List<Novel> selectByAuthorId(Long authorId) {
        return novelMapper.selectByAuthorId(authorId);
    }

    @Override
    public void updateStatusById(List<Long> id) {

    }

    /**
     * 小说审核
     * @param authorId
     * @param novelId
     */
    @GlobalTransactional
    @Transactional
    @Override
    public void novelAudit(Long authorId, List<Long> novelId) {
        Author author = authorMapper.selectById(authorId);
        if (author == null){
            throw new BusinessException("作者不存在");
        }
        List<Novel> novels = novelMapper.selectByAuthorId(authorId);
        if (novels == null){
            throw new BusinessException("作者没有作品");
        }
        novelMapper.updateStatusById(novelId,1);
    }
}